// pages/Users/AddUserAddress/AddUserAddress.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
var QQMapWX = require('../../../common/qqmap-wx-jssdk.min.js');
var qqmapsdk;
import { identficationAddress , queryAreaInfo } from '../../../api/brand';
const regeneratorRuntime = require('../../../common/runtime');
import { setAddress } from '../../../api/user';
import areaList from '../../../common/area';

Page({

    /**
     * 页面的初始数据
     */
    data: {
      shareTitle: app.globalData.global.shareTitle,
      assetsAddress: assetsAddress,
      receiver: '', // 收货人姓名
      receiverPhone: '', // 收货人手机号
      province: '',
      city: '',
      country: '',
      town: '',
      provinceCity: '', // 省市区
      latitude: '',
      longitude: '',
      detailedAddress: '', // 详细地址
      postalCode: '', // 邮政编码
      areaList: areaList,
      show: false,
      locAddressDetail: '',
      locAddressProvince: '', 
      locAddressCity: '',
      locAddressCountry: '',
      isDefault: true, // 是否默认地址
      tag: '', // 标签
      tagList: ['家','公司','学校'],
      getLat: false,
      id:'',
      autosize: { minHeight: 80 },
      provinceList: [], // 省份列表
      cityList: [], // 城市列表
      areaList: [], // 区域列表
      townList: [], // 乡镇列表
      cascaderValue: '',
      fieldNames: {
        text: 'areaName',
        value: 'areaId',
        children: 'children',
      },
      provinceId: '',
      cityId: '',
      areaId: '',
      showPrivacyAuthor: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
      qqmapsdk = new QQMapWX({
        key: 'MEZBZ-6D3O4-JPJU6-XRZRL-LH73V-PYFUZ'
      });
      // this.getUserAddress();
      if(options.item){
        var item = JSON.parse(options.item);
        console.log(item)
        this.setData({
          receiver: item.receiver,
          receiverPhone: item.receiverPhone,
          province: item.province,
          city: item.city,
          country: item.area,
          town: item.town,
          detailedAddress: item.detailedAddress,
          provinceCity: `${item.province}/${item.city}/${item.area}`,
          longitude: item.longitude,
          latitude: item.latitude,
          isDefault: item.isDefault == '1' ? true : false,
          tag: item.tag,
          id: item.id
        })
      }
      var provinceList = await this._queryAreaInfo({areaParentId: '0'})
      this.setData({
        provinceList: provinceList,
      })
      var _this = this;
      if (wx.onNeedPrivacyAuthorization){
        wx.onNeedPrivacyAuthorization((resolve) => {
          console.log('触发弹窗')
          // 触发弹窗
          _this.setData({
            showPrivacyAuthor: true,
          })
          _this.resolvePrivacyAuthorization = resolve
        })
      }  
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
      let userId = wx.getStorageSync('userId') ?? 10;
      return {
        path: '/pages/Welcome/Welcome?scene='+userId,
      }
    },
    // 获取微信地址信息
    // getWeChatAddress(){
    //   let _this = this;
    //   wx.chooseAddress({
    //     success (res) {
    //       qqmapsdk.geocoder({
    //         address: `${res.provinceName}${res.cityName}${res.countyName}${res.detailInfo}`,
    //         success: (res1)=> {
    //           console.log(res,'解析地址')
    //           if(res1.status == 0){
    //             _this.setData({
    //               receiver: res.userName,
    //               receiverPhone: res.telNumber,
    //               province: res.provinceName,
    //               city: res.cityName,
    //               country: res.countyName,
    //               provinceCity: `${res.provinceName}/${res.cityName}/${res.countyName}/${res1.result.address_components.street}`,
    //               detailedAddress: res.detailInfo,
    //               town: res1.result.address_components.street,
    //               longitude: res1.result.location.lng,
    //               latitude: res1.result.location.lat,
    //               getLat: false,
    //             })
    //           }
    //         }
    //       })
    //     },
    //     fail: (err)=> {
    //       console.log(err,'errs')
    //     }
    //   })
    // },
    // 地址解析输入框内容发生变化
    geocoderChange(e){
      console.log(e.detail)
      
      // qqmapsdk.geocoder({
      //   address: e.detail,
      //   success: (res)=> {
      //     console.log(res,'解析地址')
      //     res = res.result;
      //     _this.setData({
      //       // locAddress: res.address_component.province + ',' + res.address_component.city + ',' + res.address_component.district + ',' + res.address_component.street,
      //       longitude: res.location.lng,
      //       latitude: res.location.lat,
      //       province: res.address_components.province,
      //       city: res.address_components.city,
      //       country: res.address_components.district,
      //       detailedAddress: res.address_components.street_number ? res.address_components.street + res.address_components.street_number : res.address_component.street,
      //       provinceCity: `${res.address_components.province}/${res.address_components.city}/${res.address_components.district}`,
      //       getLat: false,
      //     })
      //   }
      // })
    },
    // 识别地址
    getAddress(){
      let _this = this;
      if(_this.data.geocoder == ''){
        wx.showToast({
          title: '请输入智能识别的收货地址',
          icon: 'none',
        })
        return;
      }
      identficationAddress({address: _this.data.geocoder})
      .then(res => {
        if(res.success){
          _this.setData({
            province: res.data.province,
            city: res.data.city,
            country: res.data.county,
            town: res.data.town,
            detailedAddress: res.data.detail,
            provinceCity: `${res.data.province}/${res.data.city}/${res.data.county}`,
            getLat: true,
            receiver: res.data.person,
            receiverPhone: res.data.phonenum,
          })
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    },
    // 点击定位
    getUserAddress(e){
      var _this = this;
      wx.getSetting({
        success: (res) => {
          console.log(res,'res')
          if(res.authSetting['scope.userFuzzyLocation']){
            _this._getFuzzy();
            // if(e){
            //   _this._getLocation();
            // }else{
            //   _this._getFuzzy();
            // }
          }else{
            wx.authorize({
              scope: 'scope.userFuzzyLocation',
              success: ()=>{
                console.log(e,'e')
                _this._getFuzzy();
                // if(e){
                //   _this._getLocation();
                // }else{
                //   _this._getFuzzy();
                // }
              },
              fail: (err) => {
                console.log(err,'err')
                wx.showModal({
                  title: '获取定位信息',
                  content: '请允许获取您的位置信息，否则小程序部分功能将无法使用',
                  success: (res) => {
                    if(res.confirm){
                      wx.openSetting({
                        success: (res) => {
                          if(res.authSetting['scope.userFuzzyLocation']){
                            // if(e){
                            //   _this._getLocation();
                            // }else{
                            //   _this._getFuzzy();
                            // }
                            _this._getFuzzy();
                          }
                        },
                      })
                    }
                  }
                })
              }
            })
          }
        },
        fail: function(err){
          console.log(err,'err')
        }
      })
    },
    // 进入页面模糊定位
    // _getFuzzy(){
    //   let _this = this;
    //   wx.getFuzzyLocation({
    //     type: 'gcj02',
    //     success: (res) => {
    //       console.log(res,'位置信息')
    //       const latitude = res.latitude
    //       const longitude = res.longitude
    //       qqmapsdk.reverseGeocoder({
    //         location: {
    //           latitude: latitude,
    //           longitude: longitude,
    //         },
    //         success: (res) => {
    //           console.log(res,'res')
    //           res = res.result;
    //           _this.setData({
    //             // locAddressProvince: res.address_component.province,
    //             // locAddressCity: res.address_component.city,
    //             // locAddressCountry: res.address_component.district,
    //             // locAddressDetail: res.address_component.street_number ? res.address_component.street + res.address_component.street_number : res.formatted_addresses.recommend ? res.formatted_addresses.recommend : res.address_component.street,
    //             // longitude: res.location.lng,
    //             // latitude: res.location.lat,
    //             // town: res.address_reference.town ? res.address_reference.town.title : res.address_component.street,
    //             longitude: res.location.lng,
    //                 latitude: res.location.lat,
    //                 province: res.address_component.province,
    //                 city: res.address_component.city,
    //                 country: res.address_component.district,
    //                 town: res.address_reference.town ? res.address_reference.town.title : res.address_component.street,
    //                 detailedAddress: res.address_component.street_number ? res.address_component.street + res.address_component.street_number : res.formatted_addresses.recommend ? res.formatted_addresses.recommend : res.address_component.street,
    //                 provinceCity: `${res.address_component.province}/${res.address_component.city}/${res.address_component.district}`,
    //                 getLat: false,
    //           })
    //         }
    //       })
    //     },
    //     fail: (err) => {
    //       console.log(err,'err')
    //     }  
    //   })
    // },
    // 使用模糊定位地址
    setAddress(){
      const {locAddressProvince , locAddressCity , locAddressCountry , locAddressDetail, town} = this.data;
      this.setData({
        province: locAddressProvince,
        city: locAddressCity,
        country: locAddressCountry,
        detailedAddress: locAddressDetail,
        provinceCity: `${locAddressProvince}/${locAddressCity}/${locAddressCountry}`,
        getLat: false,
      })
    },
    // 选择地图定位
    _getFuzzy(){
      console.log('定位')
      let _this = this;
      wx.getFuzzyLocation({
        type: 'gcj02',
        success: (res) => {
          console.log(res,'位置信息')
          const latitude = res.latitude
          const longitude = res.longitude
          wx.chooseLocation({
            latitude,
            longitude,
            success: (res)=> {
              qqmapsdk.reverseGeocoder({
                location: {
                  'latitude': res.latitude,
                  'longitude': res.longitude
                },
                success: (res)=> {
                  var res = res.result;
                  console.log(res,'解析地址')
                  _this.setData({
                    // locAddress: res.address_component.province + ',' + res.address_component.city + ',' + res.address_component.district + ',' + res.address_component.street,
                    longitude: res.location.lng,
                    latitude: res.location.lat,
                    province: res.address_component.province,
                    city: res.address_component.city,
                    country: res.address_component.district,
                    town: res.address_reference.town ? res.address_reference.town.title : res.address_component.street,
                    detailedAddress: res.address_component.street_number ? res.address_component.street + res.address_component.street_number : res.formatted_addresses.recommend ? res.formatted_addresses.recommend : res.address_component.street,
                    provinceCity: `${res.address_component.province}/${res.address_component.city}/${res.address_component.district}`,
                    getLat: false,
                  })
                },
                fail: (err)=> {
                  console.log(err,'解析错误')
                }
              })
            }
          })
        },
        fail: (err) => {
          console.log(err,'err')
        }  
      })
    },
    // 选择城市信息
    changeCity(){
      console.log(this.data.show,'show');
      this.setData({
        show: true,
      })
    },
    // 确定选择省市区
    onConfirm2(e) {
      console.log(e.detail)
      this.setData({
        provinceCity: e.detail.values[0].name + '/' + e.detail.values[1].name + '/' + e.detail.values[2].name,
        province: e.detail.values[0].name,
        city: e.detail.values[1].name,
        country: e.detail.values[2].name,
        show: false,
        getLat: false,
      })
    },
    // 是否默认地址切换
    isDefaultChange({detail}){
      this.setData({ isDefault: detail });
    },
    // 设置tag
    setTag(e){
      let _this = this;
      let item = e.target.dataset.item||e.currentTarget.dataset.item;
      _this.setData({
        tag: _this.data.tag == item ? '' : item,
      })
    },
    // 输入框发生变化
    inputChange(){
      this.setData({
        getLat: true,
      })
    },
    // 确认添加
    submit(){
      let _this = this;
      if(_this.data.receiver == ''){
        wx.showToast({
          title: '请输入收货人信息',
          icon: 'none',
        })
        return;
      }
      if(_this.data.receiverPhone == ''){
        wx.showToast({
          title: '请输入收货人电话号码',
          icon: 'none',
        })
        return;
      }
      if(_this.data.province == ''){
        wx.showToast({
          title: '请选择省市区',
          icon: 'none',
        })
        return;
      }
      if(_this.data.detailedAddress == ''){
        wx.showToast({
          title: '请输入详细地址',
          icon: 'none',
        })
        return;
      }
      var loginPhone = wx.getStorageInfoSync('phone');
      console.log(loginPhone,'loginPhone')
      if(_this.data.getLat){
        qqmapsdk.geocoder({
          address: `${_this.data.province}${_this.data.city}${_this.data.country}${_this.data.detailedAddress}`,
          success: (res)=> {
            console.log(res,'解析地址')
            res = res.result;
            _this.setData({
              // locAddress: res.address_component.province + ',' + res.address_component.city + ',' + res.address_component.district + ',' + res.address_component.street,
              longitude: res.location.lng,
              latitude: res.location.lat,
            })
            setAddress({loginPhone: loginPhone,receiver: _this.data.receiver,receiverPhone: _this.data.receiverPhone,province: _this.data.province,city: _this.data.city,area: _this.data.country,detailedAddress: _this.data.detailedAddress,isDefault: _this.data.isDefault ? '1' : '0',tag: _this.data.tag,latitude: _this.data.latitude,longitude: _this.data.longitude,id: _this.data.id,town: _this.data.town,provinceId: _this.data.provinceId,cityId: _this.data.cityId,areaId: _this.data.areaId})
            .then(res => {
              if(res.success){
                wx.showToast({
                  title: '保存成功',
                  icon: 'none',
                })
                wx.setStorageSync('country',_this.data.country);
                wx.navigateBack({
                  delta: 1,
                })
              }else{
                wx.showToast({
                  title: res.errMessage,
                  icon: 'none',
                })
              }
            })
          }
        })
      }else{
        setAddress({loginPhone: loginPhone,receiver: _this.data.receiver,receiverPhone: _this.data.receiverPhone,province: _this.data.province,city: _this.data.city,area: _this.data.country,detailedAddress: _this.data.detailedAddress,isDefault: _this.data.isDefault ? '1' : '0',tag: _this.data.tag,latitude: _this.data.latitude,longitude: _this.data.longitude,id: _this.data.id,town: _this.data.town,provinceId: _this.data.provinceId,cityId: _this.data.cityId,areaId: _this.data.areaId})
        .then(res => {
          if(res.success){
            wx.showToast({
              title: '保存成功',
              icon: 'none',
            })
            wx.setStorageSync('country',_this.data.country);
            wx.navigateBack({
              delta: 1,
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
      
    },
    // 获取省市区
    _queryAreaInfo({areaParentId}){
      return new Promise((resolve,reject) => {
        queryAreaInfo({areaParentId: areaParentId})
        .then(res => {
          if(res.success){
            resolve(res.data);
          }else{
            reject(res.errMessage)
          }
        })
      })
    },
    // _queryAreaInfo({areaParentId,type}){
    //   let _this = this;
    //   queryAreaInfo({areaParentId: areaParentId})
    //   .then(res => {
    //     if(res.success){
    //       // if(type == 0){
    //       //   _this.setData({
    //       //     provinceList: res.data,
    //       //   })
    //       //   if(res.data.length > 0){
    //       //     _this._queryAreaInfo({areaParentId: res.data[0].areaId,type: 1})
    //       //   }
    //       // }
    //       // if(type == 1){
    //       //   _this.setData({
    //       //     cityList: res.data,
    //       //   })
    //       //   if(res.data.length > 0){
    //       //     _this._queryAreaInfo({areaParentId: res.data[0].areaId,type: 2})
    //       //   }
    //       // }
    //       // if(type == 2){
    //       //   _this.setData({
    //       //     areaList : res.data,
    //       //   })
    //       //   if(res.data.length > 0){
    //       //     _this._queryAreaInfo({areaParentId: res.data[0].areaId,type: 3})
    //       //   }
    //       // }
    //       // if(type == 3){
    //       //   _this.setData({
    //       //     townList: res.data,
    //       //   })
    //       // }
    //     }else{
    //       wx.showToast({
    //         title: res.errMessage,
    //         icon: 'none',
    //       })
    //     }
    //   })
    // },
    // 选择省市区
    async onChange(e) {
      let _this = this;
      const { value } = e.detail;
      console.log(value,'value');
      if(value.substring(2) == '0000'){
        var index = _this.data.provinceList.findIndex(item => item.areaId == value);
        console.log(index,'index');
        var children = [];
        try {
          children = await _this._queryAreaInfo({areaParentId: value});
        } catch (error) {
          wx.showToast({
            title: error,
            icon: 'none',
          })
          return
        }
        var list = _this.data.provinceList;
        list[index].children = children;
        _this.setData({
          'provinceList': list,
          'provinceId': value,
          'province': list[index].areaName
        })
      }else if(value.substring(4) == '00'){
        var proIndex = _this.data.provinceList.findIndex(item => item.areaId == _this.data.provinceId);
        var index = _this.data.provinceList[proIndex].children.findIndex(item => item.areaId == value);
        var children = [];
        try {
          children = await _this._queryAreaInfo({areaParentId: value});
        } catch (error) {
          wx.showToast({
            title: error,
            icon: 'none',
          })
          return
        }
        var list = _this.data.provinceList;
        list[proIndex].children[index].children = children;
        _this.setData({
          'provinceList': list,
          'cityId': value,
          'city': list[proIndex].children[index].areaName,
        })
      }else if(value.length == 6){
        var proIndex = _this.data.provinceList.findIndex(item => item.areaId == _this.data.provinceId);
        var cityIndex = _this.data.provinceList[proIndex].children.findIndex(item => item.areaId == _this.data.cityId);
        var index = _this.data.provinceList[proIndex].children[cityIndex].children.findIndex(item => item.areaId == value);
        var children = [];
        try {
          children = await _this._queryAreaInfo({areaParentId: value});
        } catch (error) {
          wx.showToast({
            title: error,
            icon: 'none',
          })
          return
        }
        var list = _this.data.provinceList;
        list[proIndex].children[cityIndex].children[index].children = children;
        _this.setData({
          // 'provinceList': list,
          'areaId': value,
          'country': list[proIndex].children[cityIndex].children[index].areaName,
          'provinceCity': `${_this.data.province}/${_this.data.city}/${list[proIndex].children[cityIndex].children[index].areaName}`,
          show: false,
        })
      }else{
        var proIndex = _this.data.provinceList.findIndex(item => item.areaId == _this.data.provinceId);
        var cityIndex = _this.data.provinceList[proIndex].children.findIndex(item => item.areaId == _this.data.cityId);
        var areaIndex = _this.data.provinceList[proIndex].children[cityIndex].children.findIndex(item => item.areaId == _this.data.areaId);
        var index = _this.data.provinceList[proIndex].children[cityIndex].children[areaIndex].children.findIndex(item => item.areaId == value);
        _this.setData({
          'townId': value,
          'town': _this.data.provinceList[proIndex].children[cityIndex].children[areaIndex].children[index].areaName,
          'provinceCity': `${_this.data.province}/${_this.data.city}/${_this.data.country}/${_this.data.provinceList[proIndex].children[cityIndex].children[areaIndex].children[index].areaName}`,
          show: false,
        })
      }
    },
    onFinish(e) {
      const { selectedOptions, value } = e.detail;
      console.log(e,'onFinish')
      const fieldValue = selectedOptions
          .map((option) => option.text || option.name)
          .join('/');
      this.setData({
        // fieldValue,
        cascaderValue: value,
      })
    },
    onClose() {
      this.setData({
        show: false,
      });
    },
    handleAgreePrivacyAuthorizationFun(){
      console.log('同意之后的回调');
      this.getUserAddress();
    },
    disagreePrivacyAuthorization(){
      this.resolvePrivacyAuthorization({ event: 'disagree' });
    },
})